package cc.messcat.util;

import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.util.CellRangeAddress;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

public class ExcelUtil {

    private static Logger logger = LoggerFactory.getLogger(ExcelUtil.class);

    /**
     * 添加列表信息
     * sheet excelSheet
     * list 导出主要信息
     * fieldName 属性名称>数组对于表头 扩展属性格式extra.key
     * contextStyle 内容样式
     * isHaveSerial 是否添加序号
     */
    public static <T> void addContextByList(HSSFSheet sheet, List<T> list, 
            String[] field, HSSFCellStyle contextStyle,boolean isHaveSerial) {

    	if(list == null || list.isEmpty()) {
    		return;
    	}
    	boolean isMap = list.get(0) instanceof Map;
        try {
            HSSFRow row = null;
            HSSFCell cell = null;
            List<T> tList = (List<T>) list;
			T t = null;
			String value = "";
			for (int i = 0; i < list.size(); i++) {
			    row = sheet.createRow(i + 2);
			    row.setHeight((short) 430);
			    for (int j = 0; j < field.length; j++) {
			        
			        t = tList.get(i);
			        value = isMap 
			        		? objectToString(((Map)list.get(i)).get(field[j])) 
			        		: objectToString(getFieldValueByName(field[j], t));
			        if(isHaveSerial){
			            //首列加序号
			            if(row.getCell(0)==null){
			                cell = row.createCell(0);
			                cell.setCellValue(i+1+"");
			                cell.setCellStyle(contextStyle);
			            }
			            cell = row.createCell(j+1);
			            cell.setCellValue(value);    
			        }else{
			            cell = row.createCell(j);
			            cell.setCellValue(value);    
			        }
			        cell.setCellStyle(contextStyle);
			    }
			}
        } catch (Throwable e) {
            logger.error("填充内容出现错误：" + e.getMessage(), e);
        }
    }
    
    /**
     * <P>Object转成String类型，便于填充单元格</P>
     * */
    public static String objectToString(Object object){
        String str = "";
        if(object==null){
        }else if(object instanceof Date){
                DateFormat from_type = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
                Date date = (Date)object;
                str = from_type.format(date);
        }else if(object instanceof String){
            str = (String)object;
        }else if(object instanceof Integer){
            str = ((Integer)object).intValue()+"";
        }else if(object instanceof Double){
            str = ((Double)object).doubleValue()+"";
        }else if(object instanceof Long){
            str = Long.toString(((Long)object).longValue());
        }else if(object instanceof Float){
            str = Float.toHexString(((Float)object).floatValue());
        }else if(object instanceof Boolean){
            str = Boolean.toString((Boolean)object);
        }else if(object instanceof Short){
            str = Short.toString((Short)object);
        } else if(object instanceof BigInteger) {
        	str = object.toString();
        } else if(object instanceof BigDecimal) {
        	str = object.toString();
        }
        return str;
    }
    
    /**
     * 获取单元格值
     * @param cell
     */
    @Deprecated
    public static String getCellValue(HSSFCell cell) {
		
		String cellValue= "";
		DecimalFormat df = new DecimalFormat("#");
		switch(cell.getCellType()) {
			case HSSFCell.CELL_TYPE_STRING:
				cellValue= cell.getStringCellValue().trim();
				break;
			case HSSFCell.CELL_TYPE_NUMERIC: 
				cellValue= df.format(cell.getNumericCellValue()).toString();
				break;
			case HSSFCell.CELL_TYPE_BOOLEAN:  
	            cellValue = String.valueOf(cell.getBooleanCellValue()).trim();  
	            break;
			case HSSFCell.CELL_TYPE_FORMULA:  
	            cellValue = cell.getCellFormula();  
	            break;   
	        default :
	        	cellValue="";
		}
		return cellValue;
    }
    
    
    /**
     * 添加标题(第一行)与表头(第二行)
     * 
     * @param 
     * sheet excelSheet
     * cellTitle 表头>数组
     * titleName 标题 
     * headerStyle 标题样式
     * contextStyle  表头样式
     */ 
    public static void addTitle(HSSFSheet sheet, String[] cellTitle, String titleName,
            HSSFCellStyle headerStyle, HSSFCellStyle contextStyle) {
    	sheet.setColumnWidth(0, 1800);
        sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, cellTitle.length - 1));
        HSSFRow row = sheet.createRow(0);
        HSSFCell cell = row.createCell(0);
        cell.setCellValue(titleName);
        cell.setCellStyle(headerStyle);
        row = sheet.createRow(1);
        for (int i = 0; i < cellTitle.length; i++) {
            cell = row.createCell(i);
            cell.setCellValue(cellTitle[i]);
            cell.setCellStyle(contextStyle);
        }
    }

    /**
     * <p>
     * 根据属性名获取属性值
     * </p>fieldieldName 属性名 object 属性所属对象
     * 支持Map扩展属性, 不支持List类型属性，
     * return 属性值
     */
    @SuppressWarnings("unchecked")
    public static Object getFieldValueByName(String fieldName, Object object) {
        try {
            Object fieldValue = null;
            if (StringUtils.hasLength(fieldName) && object != null) {
                String firstLetter = ""; // 首字母
                String getter = ""; // get方法
                Method method = null; // 方法
                String extraKey = null;
                // 处理扩展属性 extraData.key
                if (fieldName.indexOf(".") > 0) {
                    String[] extra = fieldName.split("\\.");
                    fieldName = extra[0];
                    extraKey = extra[1];
                }
                firstLetter = fieldName.substring(0, 1).toUpperCase();
                getter = "get" + firstLetter + fieldName.substring(1);
                method = object.getClass().getMethod(getter, new Class[] {});
                fieldValue = method.invoke(object, new Object[] {});
                if (extraKey != null) {
                		/* Map<String, Object> map = (Map<String, Object>) fieldValue;
                         fieldValue = map==null ? "":map.get(extraKey);*/
						//对象.属性
						Object object2 = fieldValue;
						firstLetter = extraKey.substring(0, 1).toUpperCase();
						getter = "get" + firstLetter + extraKey.substring(1);
						method = object2.getClass().getMethod(getter, new Class[] {});
						fieldValue = method.invoke(object2, new Object[] {});
                }
            }
            return fieldValue;
        } catch (Throwable e) {
            logger.error("获取属性值出现异常：" + e.getMessage(), e);
            return null;
        }
    }
	
    
    /**
     * 表格默认标题样式
     * @param workbook
     * @return
     */
    public static HSSFCellStyle getTitleStyle(HSSFWorkbook workbook) {
    	HSSFCellStyle titleStyle =  workbook.createCellStyle();
    	HSSFFont headFont = workbook.createFont();
    	headFont.setBold(true);
    	headFont.setFontHeightInPoints((short)16);
    	titleStyle.setFont(headFont);
    	titleStyle.setAlignment(HorizontalAlignment.CENTER);
    	
    	return titleStyle;
    }
    
    /**
     * 表格默认标题样式（带换行）
     * 内容格式为 ："content \r\n content"
     * @param workbook
     * @return
     */
    public static HSSFCellStyle getWrapTitleStyle(HSSFWorkbook workbook) {
    	HSSFCellStyle titleStyle = getTitleStyle(workbook);
    	titleStyle.setWrapText(true);
    	
    	return titleStyle;
    }
    
    /**
     * 表格默认列标题样式
     * @param workbook
     * @return
     */
    public static HSSFCellStyle getColumnTitleStyle(HSSFWorkbook workbook) {
    	HSSFCellStyle columnTitleStyle =  workbook.createCellStyle();
    	columnTitleStyle.setAlignment(HorizontalAlignment.CENTER);
    	columnTitleStyle.setVerticalAlignment(org.apache.poi.ss.usermodel.VerticalAlignment.CENTER);
    	HSSFFont columnTitleFont = workbook.createFont();
    	columnTitleFont.setBold(true);
    	columnTitleFont.setFontHeightInPoints((short)11);
    	columnTitleStyle.setFont(columnTitleFont);
    	
    	return columnTitleStyle;
    }
    /**
     * 表格默认列标题样式（带换行）
     * 内容格式为 ："content \r\n content"
     * @param workbook
     * @return
     */
    public static HSSFCellStyle getWrapColumnTitleStyle(HSSFWorkbook workbook) {
	   	HSSFCellStyle columnTitleStyle =  getColumnTitleStyle(workbook);
	   	columnTitleStyle.setWrapText(true);
	   	
    	return columnTitleStyle;
    }
    
    /**
     * 表格默认单元格样式
     * @param workbook
     * @return
     */
    public static HSSFCellStyle getCellStyle(HSSFWorkbook workbook) {
    	HSSFCellStyle cellStyle =  workbook.createCellStyle(); 
    	cellStyle.setAlignment(HorizontalAlignment.CENTER);
    	cellStyle.setVerticalAlignment(org.apache.poi.ss.usermodel.VerticalAlignment.CENTER);
    	HSSFFont cellFont = workbook.createFont();
    	cellFont.setFontHeightInPoints((short)10);
    	cellStyle.setFont(cellFont);
    	
    	return cellStyle;
    }
    
    /**
     * 表格默认单元格样式（带换行）
     * 内容格式为 ："content \r\n content"
     * @param workbook
     * @return
     */
    public static HSSFCellStyle getWrapCellStyle(HSSFWorkbook workbook) {
    	HSSFCellStyle cellStyle =  getCellStyle(workbook);    	
    	cellStyle.setWrapText(true);
    	
    	return cellStyle;
    }

}
